package com.example.demo.controller;

import com.example.demo.model.dto.TaskDTO;
import org.flowable.engine.IdentityService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 经理审批控制器
 */
@RestController
@RequestMapping("/api/manager")
public class ManagerApprovalController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private IdentityService identityService;

    /**
     * 获取经理组的待审批任务
     */
    @GetMapping("/tasks")
    public ResponseEntity<List<TaskDTO>> getManagerTasks() {
        List<Task> tasks = taskService.createTaskQuery()
                .taskCandidateGroup("managers")
                .list();

        TaskDTO taskDTO = new TaskDTO();
        List<TaskDTO> taskDTOs = tasks.stream()
                .filter(task -> task != null)
                .map(taskDTO::convert)
                .collect(Collectors.toList());

        return ResponseEntity.ok(taskDTOs);
    }

    /**
     * 经理认领任务
     */
    @PostMapping("/tasks/{taskId}/claim")
    public ResponseEntity<Map<String, String>> claimTask(
            @PathVariable String taskId,
            @RequestParam String managerId) {
        
        try {
            taskService.claim(taskId, managerId);
            Map<String, String> response = new HashMap<>();
            response.put("message", "任务认领成功");
            response.put("taskId", taskId);
            response.put("managerId", managerId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("error", "任务认领失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 经理审批任务
     */
    @PostMapping("/tasks/{taskId}/approve")
    public ResponseEntity<Map<String, String>> approveTask(
            @PathVariable String taskId,
            @RequestParam String managerId,
            @RequestParam boolean approved,
            @RequestParam(required = false) String comment) {
        
        try {
            // 检查任务是否已被该经理认领
            Task task = taskService.createTaskQuery()
                    .taskId(taskId)
                    .taskAssignee(managerId)
                    .singleResult();
            
            if (task == null) {
                Map<String, String> response = new HashMap<>();
                response.put("error", "任务不存在或未被该经理认领");
                return ResponseEntity.badRequest().body(response);
            }

            // 设置审批结果
            Map<String, Object> variables = new HashMap<>();
            variables.put("approved", approved);
            if (comment != null && !comment.trim().isEmpty()) {
                variables.put("approvalComment", comment);
            }

            // 完成任务
            taskService.complete(taskId, variables);

            Map<String, String> response = new HashMap<>();
            response.put("message", approved ? "审批通过" : "审批拒绝");
            response.put("taskId", taskId);
            response.put("managerId", managerId);
            response.put("approved", String.valueOf(approved));
            if (comment != null) {
                response.put("comment", comment);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("error", "审批失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取经理已认领的任务
     */
    @GetMapping("/tasks/assigned/{managerId}")
    public ResponseEntity<List<TaskDTO>> getAssignedTasks(@PathVariable String managerId) {
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee(managerId)
                .list();

        TaskDTO taskDTO = new TaskDTO();
        List<TaskDTO> taskDTOs = tasks.stream()
                .filter(task -> task != null)
                .map(taskDTO::convert)
                .collect(Collectors.toList());

        return ResponseEntity.ok(taskDTOs);
    }

    /**
     * 创建经理用户和组（用于测试）
     */
    @PostMapping("/setup")
    public ResponseEntity<Map<String, String>> setupManager() {
        try {
            // 创建经理组
            identityService.createGroupQuery().groupId("managers").singleResult();
            if (identityService.createGroupQuery().groupId("managers").singleResult() == null) {
                org.flowable.idm.api.Group group = identityService.newGroup("managers");
                group.setName("经理组");
                group.setType("assignment");
                identityService.saveGroup(group);
            }

            // 创建经理用户
            if (identityService.createUserQuery().userId("manager1").singleResult() == null) {
                org.flowable.idm.api.User user = identityService.newUser("manager1");
                user.setFirstName("张");
                user.setLastName("经理");
                user.setEmail("manager1@company.com");
                identityService.saveUser(user);

                // 将用户添加到经理组
                identityService.createMembership("manager1", "managers");
            }

            Map<String, String> response = new HashMap<>();
            response.put("message", "经理用户和组设置完成");
            response.put("managerId", "manager1");
            response.put("groupId", "managers");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("error", "设置失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
